package com.zg.autoflow.util;

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.utils.MT;
import com.utils.RT;
import com.utils.Word2PdfUtil;
import com.zg.common.core.dao.autoform.DiyColumn;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;

@Slf4j
public class Word2PdfUtilExtend {

    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Word2PdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //显示宽度
    private final static double displaywidth = 400;

    /**
     * @param wordPath   需要被转换的word全路径带文件名
     * @param pdfPath    图片的服务器url
     * @param attachUrls 数据存储的多个图片url
     */
    public static File doc2pdf(String wordPath, String pdfPath, String[] attachUrls, Map<String, Object> map) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(RT.getRandomForWord(16) + ".pdf"); // 新建一个pdf文档
            FileOutputStream os = new FileOutputStream(pdfFile);
            Document doc = new Document(wordPath); // Address是将要被转化的word文档
            DocumentBuilder builder = new DocumentBuilder(doc);
            if (null != map && map.size() > 0) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    builder.moveToBookmark(entry.getKey());
                    builder.write(String.valueOf(entry.getValue()));
                }
            }
            for (int i = 0; i < attachUrls.length; i++) {
                log.info("attach_url=" + attachUrls[i]);
                String attachUrl = attachUrls[i];
                if (attachUrl != null && !"null".equals(attachUrl)) {
                    builder.moveToBookmark("img" + i);
                    String imgPath = pdfPath + attachUrl;
                    System.out.println("imgPath====" + imgPath);
                    BufferedImage bufferedImage = ImageIO.read(new URL(imgPath));
                    //缩放比例
                    double zoomRate = displaywidth / bufferedImage.getWidth();
                    //显示高度
                    double displayHeigth = bufferedImage.getHeight() * zoomRate;
                    builder.insertImage(imgPath, displaywidth, displayHeigth);
                }
            }
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,
            // XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            os.close();
            log.info("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static File doc2pdfNew(InputStream wordPath, String imagePath, Map<String, DiyColumn> autoFormColumnList, Map bizMap) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(RT.getRandomForWord(16) + ".pdf"); // 新建一个pdf文档
            Document doc = new Document(wordPath); // Address是将要被转化的word文档
            DocumentBuilder builder = new DocumentBuilder(doc);
            for (DiyColumn km : autoFormColumnList.values()) {
                String bookmarkWord = km.getCode();
                String valueStr = MT.getMapstr( km.getCode(), bizMap);
                boolean moveIsOk = builder.moveToBookmark(bookmarkWord);
                if (!moveIsOk) continue;
                //判断字段类型是否为file
                String control_type = km.getDataType();
                switch (control_type) {
                    case "图片": {
                        String[] values = valueStr.split(",");
                        for (String value : values) {
                            if (value.equals("")) continue;

                            builder.moveToBookmark(bookmarkWord);
                            //判断类型
                            String[] split = value.split("\\.");
                            if (split.length <= 1) {
                                continue;
                            }
                            String leixing = split[1];
                            String filePath = imagePath + value;
                            switch (leixing) {
                                case "jpeg":
                                case "jpg":
                                case "png":
                                case "gif": {
                                    BufferedImage bufferedImage = ImageIO.read(new URL(filePath));
                                    double zoomRate = displaywidth / bufferedImage.getWidth();
                                    double displayHeigth = bufferedImage.getHeight() * zoomRate;
                                    builder.insertImage(bufferedImage, displaywidth, displayHeigth);
                                }
                                break;
                                default:
                                    continue;
                            }
                        }
                    }
                    break;
                    default:
                        builder.write(valueStr);
                        break;
                }
            }
            FileOutputStream os = new FileOutputStream(pdfFile);
            doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,
            // XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            os.close();
            log.info("共耗时：" + ((now - old) / 1000.0) + "秒"); // 转化用时
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
